function scavenger() {
  this.id = 0;
  this.scavenges = new Array();
  this.selection = new Object();

  this.string_to_slug = function(str) {
    str = str.replace(/^\s+|\s+$/g, ''); // trim

    // remove accents, swap ñ for n, etc
    var from = "ÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛàáäâèéëêìíïîòóöôùúüûÑñÇç·/_,:;";
    var to   = "aaaaeeeeiiiioooouuuuaaaaeeeeiiiioooouuuunncc------";
    for (var i=0, l=from.length ; i<l ; i++) {
      str = str.replace(new RegExp(from[i], "g"), to[i]);
    }

    str = str.replace(/[^a-zA-Z0-9 -]/g, '') // remove invalid chars
      .replace(/\s+/g, '-') // collapse whitespace and replace by -
      .toLowerCase();
    return str;
  }

  this.init = function() {
    this.build();
    this.grab();

    this.selection["url"] = location.href; // document.baseURI;
    this.selection["title"] = document.title;
  };

  this.build = function() {
    if(!document.getElementById("scavenge")) {
      var css = document.createElement("link");
      css.setAttribute("href", "http://www.sellosdefutbol.com/css/favelet.css?v=8");
      css.setAttribute("rel", "stylesheet");
      css.setAttribute("type", "text/css");
      document.getElementsByTagName("head")[0].appendChild(css);
  
      var container = document.createElement("div");
      container.id = "scavenge_container";
      document.getElementsByTagName("body")[0].appendChild(container);
  
      var overlay = document.createElement("div");
      overlay.id = "scavenge";
      overlay.setAttribute("class", "scavenger");

      var html = "<div id='scavenger_msg_done'>";
      html += "<div id='scavenger_msg_header'>Added!</div>";
      html += "</div>";

      html += "<div id='scavenge_fields'>";
      html += "<label for='urlf'>URL</label>";
      html += "<input type='text' value='' id='urlf' name='urlf' size='35' />";

      html += "<label for='titlef'>TITLE</label>";
      html += "<input type='text' value='' id='titlef' name='titlef' size='35' />";

      html += "<input type='checkbox' value='' id='featured' name='featured' /><br /><br />";

      html += "<label for='categoria'>CATEGORIA</label>";
      html += "<select id='categoria' id='categoria'>";
      html+= "<option value=''></option>";
      {% for categoria in categorias %}
        html+= "<option value='{{ categoria.plural }}'>{{ categoria.plural }}</option>";
      {% endfor %}
      html += "</select>";

      html += "<label for='tag'>TAG</label>";
      html += "<select id='tag' id='tag'>";
      html+= "<option value=''></option>";
      {% for tag in tags %}
        html+= "<option value='{{ tag.plural }}'>{{ tag.plural }}</option>";
      {% endfor %}
      html += "</select>";

      html += "<label for='descrip'>DESCRIPTION</label>";
      html += "<textarea id='descrip' name='descrip' cols='30' rows='3'></textarea>";

      html += "<span id='save-btn' onclick='scavenge.send()'>SAVE</span>";
      html += "<span id='sep-btn'>|</span>";
      html += "<span id='close-btn' onclick='scavenge.close(0, 0)'> X </span>";
      html += "</div>";

      overlay.innerHTML = html;
      document.getElementsByTagName("body")[0].appendChild(overlay);
      document.getElementById("scavenge").style.display = "none";
    }
  };

  this.grab = function() {
    var images = document.getElementsByTagName("img");

    for (var i = 0; i < images.length; i++) {
      var image = images[i];

      if (image.offsetWidth >= 100 && image.offsetHeight >= 100 && image.src != '' ) {
        this.scavenges[this.id] = image;

        var width = image.offsetWidth;
        var height = image.offsetHeight;
        var left = this.positionImage(image)[0];
        var top = this.positionImage(image)[1];

        var overlay = document.createElement("div");
        overlay.id = "scavenger_overlay_" + this.id;
        overlay.setAttribute("class", "scavenger_overlay");
        overlay.style.display = "block";
        overlay.style.width = (width - 40) + "px";
        overlay.style.height = (height - 40) + "px";
        overlay.style.left = left + "px";
        overlay.style.top = top + "px";
        overlay.innerHTML = "<div id='scavenger_inner_" + this.id + "'>CLICK TO ADD</div>";
        overlay.setAttribute("onclick", "scavenge.selectImage(" + this.id + ")");
        document.getElementById("scavenge_container").appendChild(overlay);

        this.id++;
      }
    }
  };

  this.positionImage = function(pObj) {
    var posX = pObj.offsetLeft;
    var posY = pObj.offsetTop;

    while (pObj.offsetParent) {
      posX = posX + pObj.offsetParent.offsetLeft;
      posY = posY + pObj.offsetParent.offsetTop;

      if (pObj == document.getElementsByTagName("body")[0]) {
        break;
      } else {
        pObj = pObj.offsetParent;
      }
    }

    return [posX, posY];
  };

  this.selectImage = function(pId) {
    this.selection["id"] = pId;
    this.selection["image"] = this.scavenges[pId].src;

    document.getElementById("scavenger_inner_" + pId).style.display = "none";
    
    this.closeImage(pId);
    this.showOverlay();
  };

  this.closeImage = function(pId) {
    for (var i = 0; i < this.id; i++) {
      if (i != pId) {
        document.getElementById("scavenger_overlay_" + i).style.display = "none";
      }
    }
  };

  this.showOverlay = function() {
    var overlay = document.getElementById("scavenge");
    overlay.style.display = "block";
    document.getElementById("urlf").value = this.selection["url"];
    document.getElementById("titlef").value = this.selection["title"];
    document.getElementById("titlef").focus().select();
  };

  this.send = function() {
    var title = document.getElementById("titlef").value;
    var slug = this.string_to_slug(document.getElementById("titlef").value);
    var url = document.getElementById("urlf").value;
    var cat = document.getElementById("categoria").value;
    var catslug = this.string_to_slug(cat);
    var tag = document.getElementById("tag").value;
    var tagslug = this.string_to_slug(tag);
    var descrip = document.getElementById("descrip").value;
    var call = "http://www.sellosdefutbol.com/save/from_favelet?";
    call += "u=" + encodeURIComponent(url) + "&"; // URL
    call += "s=" + encodeURIComponent(slug) + "&"; // URLSLUG
    call += "i=" + encodeURIComponent(this.selection["image"]) + "&"; // IMAGEURL
    call += "t=" + encodeURIComponent(title) + "&"; // TITLE
    call += "c=" + encodeURIComponent(cat) + "&"; // CATEGORY
    call += "cs=" + encodeURIComponent(catslug) + "&"; // CATEGORYSLUG
    call += "ta=" + encodeURIComponent(tag) + "&"; // TAG
    call += "tas=" + encodeURIComponent(tagslug) + "&"; // TAGSLUG
    call += "d=" + encodeURIComponent(descrip); // DESCRIPTION
    var req = document.createElement("script");
    req.setAttribute("src", call);
    req.setAttribute( "method", 'post' );
    req.setAttribute("type", "text/javascript");
    document.getElementsByTagName("head")[0].appendChild(req);

    document.getElementById("scavenger_inner_" + this.selection["id"]).style.display = "block";
    document.getElementById("scavenger_inner_" + this.selection["id"]).innerHTML = "ADDED!";

    this.close(1, title);
  };
  
  this.close = function(pSuccess, title) {

    if(pSuccess) {
      document.getElementById("scavenge_fields").style.display = "none";
      document.getElementById("scavenger_msg_done").innerHTML = "<h1>Added!</h1> <a href='http://www.sellosdefutbol.com/sellos' parent='blank_'>http://www.sellosdefutbol.com/sellos</a>";
      document.getElementById("scavenger_msg_done").style.display = "block";
      var _self = this;
      setTimeout(function(){_self.cleanup();}, 1500);
    } else {
      document.getElementById("scavenge").style.display = "none";
      this.cleanup();
    }

    this.isGrabbing = false;
  };

  this.cleanup = function() {
    var parent = document.getElementById("scavenge_container");

    for (var i = 0; i < this.id; i++) {
      var child = document.getElementById("scavenger_overlay_" + i);
      parent.removeChild(child);
    }
    
    setTimeout(function(){
      document.getElementById("scavenge").style.display = "none";
      document.getElementById("scavenge_fields").style.display = "block";
      document.getElementById("scavenger_msg_done").style.display = "none";
         this.id = 0;
         window.scavenge_running = false;
    }, 1500);
  };

  this.init();
};

if(!window.scavenge_running) {
  window.scavenge_running = true;
  var scavenge = new scavenger();
}

